package com.reebake.ideal.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reebake.ideal.system.service.ReportService;
import com.reebake.ideal.system.vo.ReportShowQueryParamVO;
import com.reebake.ideal.system.vo.ReportShowResultVO;
import com.reebake.ideal.system.entity.Report;
import com.reebake.ideal.system.entity.ReportData;
import com.reebake.ideal.system.service.ReportDataService;
import com.reebake.ideal.system.vo.ReportDataVO;
import com.reebake.ideal.system.vo.ReportVO;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping("/analytics")
public class AnalyticsController {
    @Autowired
    private ReportService reportService;
    @Autowired
    private ReportDataService reportDataService;

    private List<Report> queryByCode(List<String> codes) {
        LambdaQueryWrapper<Report> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Report::getCode, codes);
        queryWrapper.orderByAsc(Report::getOrderNo);

        return reportService.list(queryWrapper);
    }

    private List<ReportData> queryByReportCode(List<String> reportCodes) {
        LambdaQueryWrapper<ReportData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ReportData::getReportCode, reportCodes);
        queryWrapper.orderByAsc(ReportData::getOrderNo);

        return reportDataService.list(queryWrapper);
    }

    @PostMapping("query")
    public List<ReportShowResultVO> query(@Valid @RequestBody ReportShowQueryParamVO queryParamVO) {
        List<Report> reports = queryByCode(queryParamVO.getCodes());
        List<ReportData> reportDataList = queryByReportCode(queryParamVO.getCodes());

        List<ReportShowResultVO> reportShowResultVOS = new ArrayList<>();
        for(Report report : reports){
            ReportShowResultVO reportShowResultVO = new ReportShowResultVO();
            reportShowResultVO.setReport(BeanUtil.copyProperties(report, ReportVO.class));

            for(ReportData reportData : reportDataList){
                if(report.getCode().equals(reportData.getReportCode())){
                    reportShowResultVO.getReportDataList().add(BeanUtil.copyProperties(reportData, ReportDataVO.class));
                }
            }

            reportShowResultVOS.add(reportShowResultVO);
        }
        return reportShowResultVOS;
    }

}
